<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

use mbilling\BillingBundle\Model\OrdersModel;
use mbilling\BillingBundle\Model\OrdersVpsModel;
use mbilling\BillingBundle\Model\UsersModel;
use mbilling\BillingBundle\Model\UsersBillsModel;
use mbilling\BillingBundle\Model\UsersLogsModel;
use mbilling\BillingBundle\Model\OrdersVpsTarifModel;
use mbilling\BillingBundle\Model\OrdersOSModel;
use mbilling\BillingBundle\Model\OrdersTarifsTermsModel;
use mbilling\BillingBundle\Model\OrdersIpTableModel;
use mbilling\BillingBundle\Model\OrdersIpModel;
use mbilling\BillingBundle\Model\UsersTransactionsModel;
use mbilling\BillingBundle\Model\DomainsModel;
use mbilling\BillingBundle\Model\BonusesTableModel;
use mbilling\BillingBundle\Entity\ordersVps;
use mbilling\BillingBundle\Entity\orders;
use mbilling\BillingBundle\Entity\usersBills;
use mbilling\BillingBundle\Entity\usersTransactions;
use mbilling\BillingBundle\Entity\usersLogs;
use mbilling\BillingBundle\Entity\ordersTarifsTerms;

use mbilling\BillingBundle\Form\OrdersVpsForm;
use mbilling\BillingBundle\Form\OrdersVpsAddIpForm;
use mbilling\BillingBundle\Form\OrdersVpsAddHddForm;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;

class OrdersVpsController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderVps_model = new OrdersVpsModel($em);
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();

        $group_model = new OrdersIpTableModel($em);
        $ip_model = new OrdersIpModel($em);
        $ip_string = array();

        $os_model = new OrdersOSModel($em);
        $os_string = array();

        $domain_model = new DomainsModel($em);
        $domain_string = array();

        $tarif_model = new OrdersVpsTarifModel($em);
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();   
        foreach($tarifs as $tarif)
        {
            $tarif_string[$tarif->getId()]['name'] = $tarif->getName();
            $tarif_string[$tarif->getId()]['cost'] = $tarif->getCost();
        }
        $dns_string = array();
        $gateway_string = array();
        $parameters = array();
        if ($userCurrent->isAdmin())  
        {
            if ($this->get('session')->get('user'))
                $ordersVps = $orderVps_model->findByUserId($this->get('session')->get('user')->getId());
            else
                $ordersVps = $orderVps_model->findAll();
        }
        else
            $ordersVps = $orderVps_model->findByUserId($userCurrent->getId());

        foreach($ordersVps as $orderVps)
        {
            $ip_string[$orderVps->getId()] = array();
            $ips = $ip_model->findByAccountAndType($orderVps->getName(), 2);
            $dns_string[$orderVps->getId()] = array();
            $gateway_string[$orderVps->getId()] = array();
            $domain_string[$orderVps->getId()] = array();
            foreach($ips as $ip)
            {
                array_push($ip_string[$orderVps->getId()], $ip->getIp());
                $group = $group_model->findByPK($ip->getGroupId());
                array_push($dns_string[$orderVps->getId()], $group->getDns1());
                array_push($dns_string[$orderVps->getId()], $group->getDns2());
                array_push($gateway_string[$orderVps->getId()], $group->getGateway());
            }
            $dns_string[$orderVps->getId()] = array_unique($dns_string[$orderVps->getId()]);
            $gateway_string[$orderVps->getId()] = array_unique($gateway_string[$orderVps->getId()]);
            $os = $os_model->findByPK($orderVps->getOs());
            $os_string[$orderVps->getId()] = $os->getName();

            $domains = $domain_model->findByOrderId($orderVps->getOrderId());
            foreach($domains as $domain)
            {
                $temp = array('id' => $domain->getId(), 'name' => $domain->getName());
                array_push($domain_string[$orderVps->getId()], $temp);
            }
        }
        $parameters = array('orders'   => $ordersVps,
                            'tarifs'   => $tarif_string,
                            'ips'      => $ip_string,
                            'os'       => $os_string,
                            'dnss'     => $dns_string,
                            'gateways' => $gateway_string,
                            'domains'  => $domain_string);

        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_vps:user_index.html.twig', array('parameters' => $parameters));
            else
                return $this->render('BillingBundle:Orders_vps:admin_index.html.twig', array('parameters' => $parameters));
        }
        else
            return $this->render('BillingBundle:Orders_vps:user_index.html.twig', array('parameters' => $parameters));       
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $orderVps_model = new OrdersVpsModel($em);

        $orderVps = new ordersVps();
        //$orderVps_model->create($orderVps->initDefaultEntity());//создание по умолчанию
        //return new RedirectResponse($this->generateUrl('orders_vps_show'));

        $tarif_model = new OrdersVpsTarifModel($em);
        $tarifTerms_model = new OrdersTarifsTermsModel($em);
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();
        $tarifTerms_string = array();
        foreach($tarifs as $tarif)
        {
            if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tarif->getIsActive())
            {
                $tarif_string[$tarif->getId()] = $tarif->getName().' ('.$tarif->getHdd().'Мбайт) - '.$tarif->getCost().' в день';
                $tarifsTerms = $tarifTerms_model->findByTarif($tarif->getId(), 2);
                $tarifTerm_string[$tarif->getId()] = array();
                foreach($tarifsTerms as $tarifsTerm)
                {
                    $tarifTerms_string[$tarif->getId()][$tarifsTerm->getTerm()] = $tarifsTerm->getTerm();
                }
            }
        }
        
        $os_model = new OrdersOSModel($em);
        $oss = $os_model->findAll();
        $os_string = array();
        foreach($oss as $os)
        {
            $os_string[$os->getId()] = $os->getName().' ('.$os->getPlatform().')';
        }

        $errors = array();
        if (count($tarif_string) == 0)
            array_push($errors, array('message' => 'Тарифы не созданы!', 'link' => 'vpsTarifs_add'));
        if (count($tarifTerms_string) == 0)
            array_push($errors, array('message' => 'Сроки не созданы!', 'link' => 'terms_add'));
        if (count( $os_string) == 0)
            array_push($errors, array('message' => 'Дистрибутивы не созданы!', 'link' => 'os_add'));
        if (count($errors) != 0)
        {
            if ($userCurrent->isAdmin())
            {
                if ($this->get('session')->get('user'))
                    return $this->render('BillingBundle:Orders_vps:user_error.html.twig', array('errors' => $errors));
                else
                    return $this->render('BillingBundle:Orders_vps:admin_error.html.twig', array('errors' => $errors));
            }
            else
                return $this->render('BillingBundle:Orders_vps:user_error.html.twig', array('errors' => $errors));
        }
        $form = $this->createForm(new OrdersVpsForm($tarif_string, $os_string), $orderVps);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $tarif = $tarif_model->findByPK($form['vps_tarif']->getData());
                $os = $os_model->findByPK($form['os']->getData());

                $order = new orders();
                $order->setIsActive('1');
                $order->setType('2');//VPS
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $order->setUserId($this->get('session')->get('user')->getId());
                else
                    $order->setUserId($userCurrent->getId());
                $order_model = new OrdersModel($em);

                $order_model->create($order);

                $acl = $this->get('acl');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($order, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($order, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($order);

                $orderVps_model->create($form->getData(), $os, $tarif, $order);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($orderVps, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($orderVps, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($orderVps);

                $bill_model = new UsersBillsModel($em);
                $bill = new usersBills();
                $bill->setMoney($tarif->getCost()*$tarifTerms_string[$tarif->getId()][$form['period']->getData()]*30);
                $bill->setIsReal('1');
                $bill->setIsPaid('0');
                $bill->setSourceId('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $bill->setUserId($this->get('session')->get('user')->getId());
                else
                    $bill->setUserId($userCurrent->getId());
                $bill->setCurrencyId('1');
                $bill->setOrderId($orderVps->getOrderId());
                $bill->setType('1');
                $bill->setPeriod($form['period']->getData());
                $bill_model->create($bill);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($bill, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($bill, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($bill);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('1');//создание заказа
                $log->setOrderId($orderVps->getOrderId());
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('users_bills_show'));
            }
        }

        $costById = array();
        foreach($tarifs as $tarif)
        {
            $costById[$tarif->getId()] = $tarif->getCost();
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_vps:user_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string));
            else
                return $this->render('BillingBundle:Orders_vps:admin_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string));
        }
        else
            return $this->render('BillingBundle:Orders_vps:user_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderVps_model = new OrdersVpsModel($em);

        $orderVps = $orderVps_model->findByPK($id);
        $order_id = $orderVps->getOrderId();//чтобы сохранился order_id
        $os_id = $orderVps->getOs();//чтобы сохранился os_id

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($orderVps, 'EDIT');

        $tarif_model = new OrdersVpsTarifModel($em);
        $tarifTerms_model = new OrdersTarifsTermsModel($em);
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();
        $tarifTerms_string = array();
        foreach($tarifs as $tarif)
        {
            if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tarif->getIsActive())
            {
                $tarif_string[$tarif->getId()] = $tarif->getName().' ('.$tarif->getHdd().'Мбайт) - '.$tarif->getCost().' в день';
                $tarifsTerms = $tarifTerms_model->findByTarif($tarif->getId(), 2);
                $tarifTerm_string[$tarif->getId()] = array();
                foreach($tarifsTerms as $tarifsTerm)
                {
                    $tarifTerms_string[$tarif->getId()][$tarifsTerm->getTerm()] = $tarifsTerm->getTerm();
                }
            }
        }
        
        $os_model = new OrdersOSModel($em);
        $oss = $os_model->findAll();
        $os_string = array();
        foreach($oss as $os)
        {
            $os_string[$os->getId()] = $os->getName().' ('.$os->getPlatform().')';
        }
        $form = $this->createForm(new OrdersVpsForm($tarif_string, $os_string), $orderVps);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $order_model = new OrdersModel($em);
                $order = $order_model->findByPK($order_id);
                $tarif = $tarif_model->findByPK($form['vps_tarif']->getData());
                $os = $os_model->findByPK($os_id);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $orderVps_model->update($form->getData(), $this->get('session')->get('user'), $os, $tarif, $order);
                else
                    $orderVps_model->update($form->getData(), $userCurrent, $os, $tarif, $order);
                //добавить обновление счетов

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('2');//изменение заказа
                $log->setOrderId($orderVps->getOrderId());
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('orders_vps_show'));
            }
        }
        $costById = array();
        foreach($tarifs as $tarif)
        {
            $costById[$tarif->getId()] = $tarif->getCost();
        }
        
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_vps:user_update.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'id' => $id));
            else
                return $this->render('BillingBundle:Orders_vps:admin_update.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'id' => $id));
        }
        else
            return $this->render('BillingBundle:Orders_vps:user_update.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'id' => $id));
    }
    public function extensionAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderVps_model = new OrdersVpsModel($em);

        $orderVps = $orderVps_model->findByPK($id);
        $order_id = $orderVps->getOrderId();//чтобы сохранился order_id
        $os_id = $orderVps->getOs();//чтобы сохранился os_id

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($orderVps, 'EDIT');

        $tarif_model = new OrdersVpsTarifModel($em);
        $tarifTerms_model = new OrdersTarifsTermsModel($em);
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();
        $tarifTerms_string = array();
        foreach($tarifs as $tarif)
        {
            if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tarif->getIsActive())
            {
                $tarif_string[$tarif->getId()] = $tarif->getName().' ('.$tarif->getHdd().'Мбайт) - '.$tarif->getCost().' в день';
                $tarifsTerms = $tarifTerms_model->findByTarif($tarif->getId(), 2);
                $tarifTerm_string[$tarif->getId()] = array();
                foreach($tarifsTerms as $tarifsTerm)
                {
                    $tarifTerms_string[$tarif->getId()][$tarifsTerm->getTerm()] = $tarifsTerm->getTerm();
                }
            }
        }

        $os_model = new OrdersOSModel($em);
        $oss = $os_model->findAll();
        $os_string = array();
        foreach($oss as $os)
        {
            $os_string[$os->getId()] = $os->getName().' ('.$os->getPlatform().')';
        }
        $form = $this->createForm(new OrdersVpsForm($tarif_string, $os_string), $orderVps);

        /*$bonusTable_model = new BonusesTableModel($em);
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $coupons = $bonusTable_model->findByUserIdAndActive($this->get('session')->get('user')->getId(), '1');
        else
            $coupons = $bonusTable_model->findByUserIdAndActive($userCurrent->getId(), '1');
        
        $free = false;
        if (isset($coupons['0']))
            $free = true;
        if ($free)
            $form->add(new CheckboxField('use_coupon', array('required' => false)));*/
        $free = false;
        
        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $order_model = new OrdersModel($em);
                $order = $order_model->findByPK($order_id);
                $tarif = $tarif_model->findByPK($form['vps_tarif']->getData());
                $os = $os_model->findByPK($os_id);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $orderVps_model->update($form->getData(), $this->get('session')->get('user'), $os, $tarif, $order);
                else
                    $orderVps_model->update($form->getData(), $userCurrent, $os, $tarif, $order);

                $bill_model = new UsersBillsModel($em);
                $bill = new usersBills();
                /*if ($form['use_coupon']->getData())//перенести в счета
                {
                    $bill->setMoney('0');
                    $bill->setIsPaid('1');
                    $coupon = $coupons['0'];
                    $coupon->setUsedAt(new \DateTime());
                    $bonusTable_model->create($coupon);
                }
                else
                {*/
                    $bill->setMoney($tarif->getCost()*$tarifTerms_string[$tarif->getId()][$form['period']->getData()]*30);
                    $bill->setIsPaid('0');
                //}
                $bill->setIsReal('1');
                $bill->setSourceId('0');
                $bill->setPeriod($form['period']->getData());
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $bill->setUserId($this->get('session')->get('user')->getId());
                else
                    $bill->setUserId($userCurrent->getId());
                $bill->setCurrencyId('1');
                $bill->setOrderId($orderVps->getOrderId());
                $bill->setType('2');
                $bill_model->create($bill);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($bill, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($bill, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($bill);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('7');//продление заказа
                $log->setOrderId($orderVps->getOrderId());
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('users_bills_show'));
            }
        }
        $costById = array();
        foreach($tarifs as $tarif)
        {
            $costById[$tarif->getId()] = $tarif->getCost();
        }

        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_vps:user_extension.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'id' => $id, 'use_coupon' => $free));
            else
                return $this->render('BillingBundle:Orders_vps:admin_extension.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'id' => $id, 'use_coupon' => $free));
        }
        else
            return $this->render('BillingBundle:Orders_vps:user_extension.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'id' => $id, 'use_coupon' => $free));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderVps_model = new OrdersVpsModel($em);
        $order_model = new OrdersModel($em);

        $orderVps = $orderVps_model->findByPK($id);
        $order = $order_model->findByPK($orderVps->getOrderId());

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($order, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($order, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($order, $userCurrent);
        $acl->removePermissionsForAllAdmins($order);
        $acl->checkPermissions($orderVps, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($orderVps, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($orderVps, $userCurrent);
        $acl->removePermissionsForAllAdmins($orderVps);
        
        $order_model->removeByPK($orderVps->getOrderId());

        $bill_model = new UsersBillsModel($em);
        $bill = $bill_model->findByOrderId($orderVps->getOrderId());
        $acl->checkPermissions($bill, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($bill, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($bill, $userCurrent);
        $acl->removePermissionsForAllAdmins($bill);
        
        $bill_model->removeByOrderId($orderVps->getOrderId());
        
        $orderVps_model->removeByPK($id);

        $log_model = new UsersLogsModel($em);
        $log = new usersLogs();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $log->setUserId($this->get('session')->get('user')->getId());
        else
            $log->setUserId($userCurrent->getId());
        $log->setActionTypeId('3');//удаление заказа
        $log->setOrderId($orderVps->getOrderId());
        $log_model->create($log);

        return new RedirectResponse($this->generateUrl('orders_vps_show'));
    }
    public function add_IpAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderVps_model = new OrdersVpsModel($em);
        $tarif_model = new OrdersVpsTarifModel($em);
        $group_model = new OrdersIpTableModel($em);
        $ip_model = new OrdersIpModel($em);
        $os_model = new OrdersOSModel($em);
        $order_model = new OrdersModel($em);
        $bill_model = new UsersBillsModel($em);
        
        $orderVps = $orderVps_model->findByPK($id);
        $groups = $group_model->findAll();
        $tarif = $tarif_model->findByPK($orderVps->getVpsTarif());
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        
        $count = 0;
        $form = $this->createForm(new OrdersVpsAddIpForm, $count);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $count = $form['count']->getData();
                $suc_inserted = 0;
                while ($count > 0)
                {
                    foreach ($groups as $group)
                    {
                        $inserted = false;
                        $free_ips = $ip_model->findFree($group->getId());
                        $free_ip = $free_ips[0];
                        if (isset($free_ip))
                        {
                            if ($count > 0)
                            {
                                $free_ip->setTypeId('2');
                                $free_ip->setAccount($orderVps->getName());
                                $ip_model->create($free_ip);
                                $inserted = true;
                                $suc_inserted++;
                                $count--;
                            }
                        }
                    }
                    if (!$inserted)
                        break;//+отсылать сообщение админу
                }
                $orderVps->setDedIpCount($orderVps->getDedIpCount() + $suc_inserted);
                $os = $os_model->findByPK($orderVps->getOs());
                $order = $order_model->findByPK($orderVps->getOrderId());

                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $orderVps_model->update($orderVps, $this->get('session')->get('user'), $os, $tarif, $order);
                else
                    $orderVps_model->update($orderVps, $userCurrent, $os, $tarif, $order);

                $transaction_model = new UsersTransactionsModel($em);
                $transaction = new usersTransactions();
                $transaction->setMoney($suc_inserted * $tarif->getAddIpCost());
                $transaction->setOrderId($order->getId());
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $transaction->setUserId($this->get('session')->get('user')->getId());
                else
                    $transaction->setUserId($userCurrent->getId());
                $bill = $bill_model->findByOrderId($order->getId());
                $transaction->setBillId($bill->getId());
                $transaction->setIsAdding('0');
                $transaction->setIsRegular('1');
                $transaction_model->create($transaction);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('4');//заказ дополнительного ip адреса
                $log->setOrderId($order->getId());
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('orders_vps_show'));
            }
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_vps:user_add_ip.html.twig', array('form' => $form->createView(), 'tarif' => $tarif));
            else
                return $this->render('BillingBundle:Orders_vps:admin_add_ip.html.twig', array('form' => $form->createView(), 'tarif' => $tarif));
        }
        else
            return $this->render('BillingBundle:Orders_vps:user_add_ip.html.twig', array('form' => $form->createView(), 'tarif' => $tarif));
    }
    public function add_HddAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderVps_model = new OrdersVpsModel($em);
        $tarif_model = new OrdersVpsTarifModel($em);
        $os_model = new OrdersOSModel($em);
        $order_model = new OrdersModel($em);
        $bill_model = new UsersBillsModel($em);
        
        $orderVps = $orderVps_model->findByPK($id);
        $tarif = $tarif_model->findByPK($orderVps->getVpsTarif());

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();

        $value = 0;
        $form = $this->createForm(new OrdersVpsAddHddForm, $value);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $value = $form->get('value')->getDisplayedData();
                $orderVps->setHdd($orderVps->getHdd() + $value);
                $orderVps->setIsChanged('1');
                $os = $os_model->findByPK($orderVps->getOs());
                $order = $order_model->findByPK($orderVps->getOrderId());

                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $orderVps_model->update($orderVps, $this->get('session')->get('user'), $os, $tarif, $order);
                else
                    $orderVps_model->update($orderVps, $userCurrent, $os, $tarif, $order);

                $transaction_model = new UsersTransactionsModel($em);
                $transaction = new usersTransactions();
                $transaction->setMoney($value * $tarif->getAddHddCost());
                $transaction->setOrderId($order->getId());
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $transaction->setUserId($this->get('session')->get('user')->getId());
                else
                    $transaction->setUserId($userCurrent->getId());
                $bill = $bill_model->findByOrderId($order->getId());
                $transaction->setBillId($bill->getId());
                $transaction->setIsAdding('0');
                $transaction->setIsRegular('1');
                $transaction_model->create($transaction);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('5');//заказ дополнительного места на hdd
                $log->setOrderId($order->getId());
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('orders_vps_show'));
            }
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_vps:user_add_hdd.html.twig', array('form' => $form->createView(), 'tarif' => $tarif));
            else
                return $this->render('BillingBundle:Orders_vps:admin_add_hdd.html.twig', array('form' => $form->createView(), 'tarif' => $tarif));
        }
        else
            return $this->render('BillingBundle:Orders_vps:user_add_hdd.html.twig', array('form' => $form->createView(), 'tarif' => $tarif));
    }
}